﻿#define DEBUG_STATE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using Microsoft.Win32;
using CSBackup.Src.Override;
using System.Threading;
using System.IO;

namespace BackupService
{
    class BackupService : ServiceBase
    {
        private bool _running = true;

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            ThreadStart start = new ThreadStart(this.Loop);
            Thread thread = new Thread(start);
            thread.Start();
        }

        private void Loop()
        {
            while (this._running)
            {
                try
                {
                    RegistryKey key = Registry.LocalMachine.OpenSubKey("software").OpenSubKey("YunGe", true);
                    string[] keyNames = key.GetSubKeyNames();
                    foreach (string sub in keyNames)
                    {
                        RegistryKey subKey = key.OpenSubKey(sub, true);
                        string intervalStr = subKey.GetValue("interval") as string;
                        string startTimeStr = subKey.GetValue("startTime") as string;
                        string endTimeStr = subKey.GetValue("endTime") as string;
                        string repeatStr = subKey.GetValue("repeatCount") as string;
                        string lastStr = subKey.GetValue("lastBackup") as string;
                        string prjPath = subKey.GetValue("prjPath") as string;

                        DateTime startTime = DateTime.Parse(startTimeStr);
                        DateTime endTime = DateTime.Parse(endTimeStr);
                        //如果在规定的备份时间内
                        if (DateTime.Now.CompareTo(startTime) > 0 && DateTime.Now.CompareTo(endTime) < 0)
                        {
                            int interval = Convert.ToInt32(intervalStr);
                            DateTime last = DateTime.Parse(lastStr);
                            TimeSpan span = DateTime.Now - last;
                            if (span.TotalMinutes > interval)
                            {
                                int repeatCount = Convert.ToInt32(repeatStr);
                                if (repeatCount != 0)
                                {
                                    subKey.SetValue("lastBackup", DateTime.Now.ToString());
                                    this.DoBackup(BackupInfo.BACKUP_TYPE_FULL, prjPath);
                                    if (repeatCount != -1)
                                    {
                                        subKey.SetValue("repeatCount", repeatCount - 1);
                                    }
                                }
                            }
                        }//if
                    }// foreach (string sub in keyNames)
                    key.Close();
                }
                catch (Exception ex)
                {
                    #if DEBUG_STATE
                    
                    this.LogException(ex);
                    
                    #endif
                }
                Thread.Sleep(1000);
            }
        }

        private void LogException(Exception ex)
        {
            StreamWriter writer = new StreamWriter("d:/tmp/ex.txt", true);
            writer.Write(DateTime.Now.ToLongDateString() + ": ");
            writer.WriteLine(ex.ToString());
            writer.Close();
        }

        protected override void OnStop()
        {
            base.OnStop();
            this._running = false;
        }

        public void DoBackup(string type, string prjPath)
        { 
            ProjectInfo info = new ProjectInfo();
            ToolConfigFile.LoadPrjFromFile(info, prjPath);

            BackupExport.BackUp(info.BkpPrjFile, info.CurrentBackup.FileList.ToArray(), info.CurrentBackup.FileList.Count,
                                                   type, null, "Data");

        }

        private void InitializeComponent()
        {
            // 
            // BackupService
            // 
            this.ServiceName = "BackupService";

        }
        /*
        public void DoBackup(string type, string path)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey("software").OpenSubKey("YunGe");
            string[] names = key.GetValueNames();
            List<ProjectInfo> prjList = new List<ProjectInfo>();
            //load all projects
            foreach (string name in names)
            {
                if (name.StartsWith("back"))
                {
                    string path = key.GetValue(name) as string;
                    ProjectInfo info = new ProjectInfo();
                    ToolConfigFile.LoadPrjFromFile(info, path);
                    prjList.Add(info);
                }
            }

            //do backup for each project
            foreach (ProjectInfo pInfo in prjList)
            {
                List<string> pathList = new List<string>();

                foreach (BackupInfo bInfo in pInfo.FullBackupList)
                {
                    pathList.Add(bInfo.BkpLocation);
                }
                BackupExport.BackUp(pInfo.BkpPrjFile, pathList.ToArray(), pathList.Count, type, null, "Data");
               // BackupWorker worker = new BackupWorker(pInfo.BkpPrjFile, pathList, "Full", null, "Data");
                //worker.RunWorkerAsync();
            }
            key.Close();
        }*/
    }
}
